<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="1350px" :clickModalClose="true" @close="handleClose"
            :footershow="false">
            <div class="bor">
                <!-- 添加编辑的时候隐藏印章图片&& editshow -->
                <div v-if="popupTitle != '新增报废单' && editshow" class="zhangMain">
                    <img v-if="list.status_name == '待入库'" class="zhang" :src="dairuku" alt="">
                    <img v-if="list.status_name == '待出库'" class="zhang" :src="daichuku" alt="">
                    <img v-if="list.status_name == '已入库'" class="zhang" :src="yiruku" alt="">
                    <img v-if="list.status_name == '已作废'" class="zhang" :src="yizuofei" alt="">
                    <img v-if="list.status_name == '已驳回'" class="zhang" :src="yibohui" alt="">
                    <img v-if="list.status_name == '待审核'" class="zhang" :src="daishenhe" alt="">
                    <img v-if="list.status_name == '已报废'" class="zhang" :src="yibaofei" alt="">
                    <img v-if="list.status_name == '待报废'" class="zhang" :src="daibaofei" alt="">
            
                </div>
                <el-form ref="formRef" :model="list" label-width="120px" :rules="formRules" label-position="right">
                    <el-row>
                        <el-col :span="span" v-if="popupTitle != '新增报废单'">
                            <el-form-item label="单据编号" prop="order_no">
                                <p class="fontcolor">{{ list.order_no || noData }}</p>
                            </el-form-item>
                        </el-col>
                        <el-col :span="span" v-if="popupTitle != '新增报废单'">
                            <el-form-item label="单据类型" prop="type_name">
                                <p class="fontcolor">{{ list.type_name || noData }}</p>
                            </el-form-item>
                        </el-col>

                        <el-col :span="span" v-if="popupTitle != '新增报废单'">
                            <el-form-item label="创单人" prop="user_name">
                                <p class="fontcolor">{{ list.user_name || noData }}</p>
                            </el-form-item>
                        </el-col>
                        <el-col :span="span" v-if="popupTitle != '新增报废单'">
                            <el-form-item label="创单时间" prop="create_time">
                                <p class="fontcolor">{{ list.create_time || noData }}</p>
                            </el-form-item>
                        </el-col>
                        <el-col :span="span">
                            <el-form-item label="报废仓库" prop="warehouse_id">
                                <el-select v-if="formData.root !== 1" class="flex-1" v-model="list.warehouse_id"
                                    placeholder="请输入报废仓库" size="small" @change="onoutbound_warehouse_id">
                                    <el-option v-for="(item, index) in options.listColumn" :key="index" :label="item.title"
                                        :value="item.id"></el-option>
                                </el-select>
                                <fontGoBeyond v-if="formData.root == 1" :text="list.warehouse_name" />
                            </el-form-item>
                        </el-col>
                        <el-col v-if="popupTitle != '新增报废单' && list.out_confirm_user_name" :span="span">
                            <el-form-item label="出库人" prop="out_confirm_user_name">
                                <p class="fontcolor">{{ list.out_confirm_user_name || noData }}</p>
                            </el-form-item>
                        </el-col>
                        <el-col v-if="popupTitle != '新增报废单' && list.out_confirm_time" :span="span">
                            <el-form-item label="出库时间" prop="out_confirm_time">
                                <p class="fontcolor">{{ list.out_confirm_time || noData }}</p>
                            </el-form-item>
                        </el-col>
                        <el-col :span="span">
                            <el-form-item label="申请人" prop="applicant_user_id">
                                <p v-if="list.applicant_user_name">{{ list.applicant_user_name }}</p>
                                <el-select v-if="popupTitle == '新增报废单'" :no-data-text="`请先选择报废仓库`" @focus="onfocusren"
                                    :disabled="formData.root == 1" class="flex-1" v-model="list.applicant_user_id"
                                    placeholder="请输入申请人" size="small">
                                    <el-option v-for="(item, index) in options.alluser" :key="index" :label="item.name"
                                        :value="item.id"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="span">
                            <el-form-item label="货单单号" prop="delivery_no">
                                <el-input v-if="formData.root !== 1" v-model="list.delivery_no" placeholder="请输入货单单号"
                                    size="small">
                                </el-input>
                                <p v-else class="fontcolor">{{ list.delivery_no || noData }}</p>
                            </el-form-item>
                        </el-col>
                        <el-col :span="span">
                            <el-form-item label="货单编号">
                                <el-input v-if="formData.root !== 1" v-model="list.delivery_number" placeholder="请输入货单编号"
                                    size="small">
                                </el-input>
                                <p v-else class="fontcolor">{{ list.delivery_number || noData }}</p>
                            </el-form-item>
                        </el-col>
                        <el-col :span="span">
                            <el-form-item label="货单日期" prop="delivery_date">
                                <div class="span">
                                    <el-date-picker v-if="formData.root !== 1" v-model="list.delivery_date"
                                        format="YYYY/MM/DD" value-format="YYYY-MM-DD" :disabled-date="disabledDate"
                                        type="date" placeholder="请输入货单日期" size="small" />
                                    <p v-else class="fontcolor">{{ list.delivery_date || noData }}</p>
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="span" v-if="popupTitle != '新增报废单'">
                            <el-form-item label="审核人" prop="review_user_name">
                                <p class="fontcolor">{{ list.review_user_name || noData }}</p>
                            </el-form-item>
                        </el-col>
                        <el-col :span="span" v-if="popupTitle != '新增报废单'">
                            <el-form-item label="审核时间" prop="review_time">
                                <p class="fontcolor">{{ list.review_time || noData }}</p>
                            </el-form-item>
                        </el-col>
                        <el-col :span="span" v-if="popupTitle != '新增报废单'">
                            <el-form-item label="报废时间" prop="confirm_time">
                                <p class="fontcolor">{{ list.confirm_time || noData }}</p>
                            </el-form-item>
                        </el-col>
                        <el-col :span="18" v-if="popupTitle == '新增报废单'">

                        </el-col>

                        <el-col :span="12" v-if="list.type_name == '调拨单' && list.status_name == '待出库'"
                            style="border-right: none;"></el-col>
                        <el-col :span="18" v-if="list.type_name == '入库单'" style="border-right: none;"></el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24" style="border-right:none ;">
                            <el-form-item label="照片">
                                <div>
                                    <div class="flex">
                                        <material-picker :disabled="formData.root == 1" :photoHide="editshow"
                                            v-model="list.delivery_image" :limit="99" />
                                        <div v-if="popupTitle == '新增报废单'" class="font-t">建议尺寸：100*100px，支持jpg，jpeg，png格式
                                        </div>
                                    </div>
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24" style="border-right:0;">
                            <el-form-item label="附件">
                                <div>
                                    <div class="flex">
                                        <material-picker :disabled="formData.root == 1" :photoHide="editshow"
                                            v-model="list.attachment" :typeshow="true" :img="false" :limit="99" />
                                        <div v-if="popupTitle == '新增报废单'" class="font-t">
                                            建议格式：pdf，doc，docx，ppt，xls，xlsx，zip，rar</div>
                                    </div>
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24" style="border-right:none ;">
                            <el-form-item label="备注" prop="remark">
                                <el-input v-if="formData.root !== 1" v-model="list.remark" type="textarea"
                                    placeholder="请输入备注" autosize size="small"></el-input>
                                <p v-else class="fontcolor">{{ list.remark || noData }}</p>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <mtable :warehouse_id="warehouse_id" @onShowtables="onShowtables" :type="list.type_name" @onfocus="onShowtables"
                :tableName="false" :disableds="popupTitle" :mode="editshow" :type_name="popupTitle" :levelType="levelType">
            </mtable>
            <div class="buts">
                <div v-if="list.permissions.confirm">
                    <!-- <el-button v-if="list.status_name=='待入库'" class="f-left" type="primary"
						@click="onadminconfirmOrder(1)">
						确认入库
					</el-button>
					<el-button v-if="list.status_name=='待出库'" class="f-left" type="primary"
						@click="onadminconfirmOrder(2)">
						确认出库
					</el-button> -->
                    <el-button v-if="list.status_name == '待报废'" class="f-left" type="primary"
                        @click="onadminconfirmOrder(2)">
                        确认报废
                    </el-button>
                </div>
                <el-button type="primary" class="f-left" v-if="list.permissions.edit & editshow" @click="handleType">
                    编辑
                </el-button>
                <el-button type="primary" class="f-left" v-if="list.permissions.edit & !editshow" @click="handleSubmit">
                    保存
                </el-button>
                <el-button type="danger" class="f-left" v-if="list.permissions.reject" @click="onadminupdateStatus(20)">
                    驳回
                </el-button>
                <el-button type="success" class="f-left" v-if="list.permissions.review" @click="onadminupdateStatus(60)">
                    审核通过
                </el-button>
                <el-button type="" class="f-left" v-if="list.permissions.close" @click="onadminupdateStatus(40)">
                    作废
                </el-button>
                <el-button type="primary" class="f-left" v-if="mode == 'add'" @click="handleSubmit">确认</el-button>
                <el-button class="f-left" v-if="mode == 'add'" @click="handleCancel">取消</el-button>
            </div>
            <treeText :data="list.record"></treeText>
        </popup>
    </div>
</template>
<script lang="ts" setup>
import dairuku from '@/assets/images/dairuku.png'
import daichuku from '@/assets/images/daichuku.png'
import yiruku from '@/assets/images/yiruku.png'
import yizuofei from '@/assets/images/yizuofei.png'
import yibohui from '@/assets/images/yibohui.png'
import daishenhe from '@/assets/images/daishenhe.png'
import  yibaofei from '@/assets/images/yibaofei.png'
import daibaofei from '@/assets/images/daibaofei.png'
import type {
    FormInstance
} from 'element-plus'
import fontGoBeyond from '@/components/fontGoBeyond/index.vue'
import feedback from '@/utils/feedback'
import Popup from '@/components/popup/index.vue'
import treeText from '@/components/treeText/index.vue'
import mtable from '../components/tableone.vue'
import {
    adminAdd,
    adminEdit,
    adminconfirmOrder,
    adminDetail,
    admincheckWarehouse,
    adminupdateStatus,
    userBind,
    getListren
} from '@/api/delete/list'
import {
    tableListing
} from '@/utils/tableData'
import {
    getType
} from '@/api/tools/code'
import useUserStore from '@/stores/modules/user';
import useAppStore from '@/stores/modules/inventory';
import { orderNotice, scrapOrderNotice,financeOrderNotice } from "@/api/tools/code";
const userStore1 = useUserStore();
const emit = defineEmits(['success', 'close'])
const warehouse_id = ref('')
const userStore = useAppStore()
const tableList = computed(() => userStore.tableList)
const span = ref(6)
const formRef = ref<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const noData = ref('')
const formData = reactive({
    id: '',
    status_name: '',
    warehouse_id: '',
    delivery_unit: '',
    delivery_tel: '',
    attachment: [],
    review_time: '',
    confirm_time: '',
    delivery_date: '',
    outbound_warehouse_id: '',
    delivery_plate_number: '',
    delivery_no: '',
    delivery_image: [],
    permissions: {},
    remark: '',
    type: 30,
    type_name: '',
    items: '',
    root: 0
})


const disabledDate = (time: Date) => {
    return time.getTime() > Date.now()
}

const popupTitle = computed(() => {
    userStore.onpopupTitle('20')
    if ((mode.value == 'add')) {
        formData.root = 0
        editshow.value = false
        return '新增报废单'
    } else {
        formData.root = 1
        editshow.value = true
        userStore.onnumshow(true)
        return '详情'
    }

})

const list = reactive({
    id: '',
    order_no: '',
    warehouse_id: '',
    applicant_user_id: '',
    status_name: '',
    delivery_unit: '',
    delivery_tel: '',
    delivery_plate_number: '',
    delivery_no: '',
    delivery_image: [],
    remark: '',
    outbound_warehouse_id: '',
    type: 30,
    attachment: [],
    delivery_number: '',
    delivery_date: '',
    review_time: '',
    confirm_time: '',
    user_name: '',
    list_edit: '',
    permissions: {},
    outbound_warehouse_name: '',
    type_name: '',
    applicant_user_name: '',
    warehouse_name: '',
    confirm_user_name: '',
    out_confirm_user_name: '',
    review_user_name: '',
    create_time: '',
    out_confirm_time: '',
    items: '',
    record: []
})

const type = ref('')
watch(formData, (newValue, oldValue) => {
    let val = JSON.stringify(newValue)
    id.value = JSON.parse(val).id
    type.value = JSON.parse(val).type
    tableing()
})
watch(() => [list.outbound_warehouse_id, list.warehouse_id], (newValue) => {
    warehouse_id.value = newValue[1]
    userStore.onwarehouse_id(newValue[1])
}, {
    deep: true
})
watch(() => [list.warehouse_id], (newValue) => {
    if (newValue[0] != 0) {
        ongetType(newValue[0])
    }
}, {
    deep: true
})
const ondelivery_tel = (val: any) => {
    let reg = /^1[345789]\d{9}$/
    if (reg.test(val) == false) {
        return feedback.msgError(`请输入正确手机号`)
    }
}
const editshow = ref(true)
const onoutbound_warehouse_id = (val: any) => {
    userStore.tableListdata(tableListing())
    ongetType(val)
    userStore.onnumshow(false)
}

const levelType = ref()
const ongetType = (id: any) => {
    getType({
        warehouse_id: id
    }).then((data: any) => {
        // 1公司级2项目级
        levelType.value = data.level
    })
}

const handleType = () => {
    editshow.value = false
    formData.root = 0
    if (list.warehouse_id) {
        ongetType(list.warehouse_id)
    }
}
const onShowtables = async () => {
    await formRef.value?.validate((valid, fields) => {
        if (valid) { } else { }
    })
}
const dataList = ref()
const tableing = () => {
    adminDetail({
        id: id.value
    }).then((data: any) => {
        dataList.value = data
        list.id = data.id
        list.record = data.record
        list.order_no = data.order_no
        list.status_name = data.status_name
        list.warehouse_id = data.warehouse_id
        list.outbound_warehouse_id = data.outbound_warehouse_id
        list.delivery_unit = data.delivery_unit
        list.delivery_tel = data.delivery_tel
        list.applicant_user_id = data?.applicant_user_id
        list.attachment = data?.attachment
        list.delivery_plate_number = data.delivery_plate_number
        list.delivery_no = data.delivery_no
        list.applicant_user_name = data?.applicant_user_name
        list.review_user_name = data.review_user_name
        list.review_time = data.review_time
        list.confirm_time = data.confirm_time
        list.delivery_image = data.delivery_image
        list.confirm_time = data.confirm_time
        list.confirm_user_name = data.confirm_user_name
        list.out_confirm_time = data.out_confirm_time
        list.out_confirm_user_name = data.out_confirm_user_name
        list.create_time = data.create_time
        list.user_name = data.user_name
        list.type_name = data.type_name
        list.delivery_date = data.delivery_date
        list.delivery_number = data.delivery_number
        list.permissions = data.permissions
        list.list_edit = data?.permissions.list_edit || ''
        list.remark = data.remark
        list.type = data.type
        list.outbound_warehouse_name = data.outbound_warehouse_name
        list.warehouse_name = data.warehouse_name
        let ss = data.orderData
        let jj = JSON.parse(data.items)
        for (let i = 0; i < ss.length; i++) {
            jj[i].quantity = ss[i].quantity
            jj[i].total_price = ss[i].total_price
            jj[i].cargo_weight = ss[i].cargo_weight
            jj[i].remark = ss[i].remark
        }
        list.items = jj
        userStore.tableListdata(jj)
        if (list.type == 10) {
            onbuttype(list.warehouse_id)
        } else {
            onbuttype(list.outbound_warehouse_id)
        }
    })
}

const formRules = reactive({
    warehouse_id: [{
        required: true,
        message: '请输入报废仓库',
        trigger: ['change']
    }],
    delivery_unit: [{
        required: true,
        message: '请输入送货单位',
        trigger: ['blur']
    }],
    applicant_user_id: [{
        required: true,
        message: '请输入申请人',
        trigger: ['change']
    }]
})
const id = ref('')
const options = reactive({
    listColumn: [] as any[],
    listUserBind: [] as any[],
    listUserBinds: [] as any[],
    alluser: [] as any[]
})
const butshow = ref(false)
const onbuttype = (id: any) => {
    admincheckWarehouse({
        warehouse_id: id
    }).then((data: any) => {
        butshow.value = data.data
    })
}
const onadminupdateStatus = async (status: any) => {
    if (status == 40) {
        await feedback.confirm('单据作废，无法恢复')
        await adminupdateStatus({
            id: id.value,
            status: status,
            data: dataList.value
        }).then((data: any) => {
            formRef.value?.validate()
            popupRef.value?.close()
            emit('success')
        })
    } else if (status == 60) {
        await feedback.confirm('审核通过后，物料将进行报废确认。', true, '再想一想', '确认')
        await adminupdateStatus({
            id: id.value,
            status: status,
            data: dataList.value
        }).then((data: any) => {
            formRef.value?.validate()
            popupRef.value?.close()
            emit('success')
        })
    } else {
        adminupdateStatus({
            id: id.value,
            status: status,
            data: dataList.value
        }).then((data: any) => {
            formRef.value?.validate()
            popupRef.value?.close()
            emit('success')
        })
    }

}
const onfocusren = () => {
    getListren({
        warehouse_id: list.warehouse_id
    }).then((data: any) => {
        options.alluser = data
    })
}

const getOptions = () => {
    userBind({
        is_order: 2
    }).then((data: any) => {
        options.listColumn = data
    })


}
const onadminconfirmOrder = async (type: any) => {
    if (type == 1) {
        await feedback.confirm('确认入库后，物料入库数量无法修改', true, '再想一想', '确认入库')
        await adminconfirmOrder({
            id: id.value,
            data: dataList.value
        }).then((data: any) => {
            formRef.value?.validate()
            popupRef.value?.close()
            emit('success')
        })
    } else {
        await feedback.confirm('确认报废后，物料无法修改', true, '再想一想', '确认报废')
        await adminconfirmOrder({
            id: id.value,
            data: dataList.value
        }).then((data: any) => {
            formRef.value?.validate()
            popupRef.value?.close()
            emit('success')
            // userStore.onnumberMenu(true)
            onNum();
        })
    }

}
//高扬添加
//修改了红点不更新的问题
const onNum = () => {
    orderNotice().then((data: any) => {
        for (let i = 0; i < userStore1.routes?.length; i++) {
            if (userStore1.routes[i].meta.title == "单据详情") {
                userStore1.routes[i].meta.total = data.total;
            }
        }
    });
    // lqy获取请款单详情数量
          financeOrderNotice().then((data: any) => {
        if (data) {
            for (let i = 0; i < userStore1.routes?.length; i++) {
                if (userStore1.routes[i].meta.title == '财务管理') {
                    if (userStore1.routes[i].children?.length != 0&&userStore1.routes[i].children.find(x=>x.meta.title==='请款单详情')) {
                        userStore1.routes[i].children[userStore1.routes[i].children.findIndex(x=>x.meta.title==='请款单详情')].meta.total = data.total
                    }
                }
            }
        }
    })
        
    scrapOrderNotice().then((data: any) => {
        if (data) {
            for (let i = 0; i < userStore1.routes?.length; i++) {
                if (userStore1.routes[i].meta.title == "报废管理") {
                    if (userStore1.routes[i].children?.length != 0) {
                        userStore1.routes[i].children[1].meta.total = data.total;
                    }
                }
            }
        }
    });
};

const onadminEdit = () => {
    adminEdit(list).then((data: any) => {
        popupRef.value?.close()
        emit('success')
        userStore.offwarehouse_id()
    })
}
const onadminEdits = () => {
    adminAdd(list).then((data: any) => {
        popupRef.value?.close()
        emit('success')

    })
}
const handleCancel = async () => {
    list.warehouse_id = ''
    emit('close')
}
const handleSubmit = async () => {
    if (list.type_name == '') {
        if (list.warehouse_id) {
            if (list.applicant_user_id) {

            } else {
                feedback.msgError(`请先填写报废申请人`)
            }
        } else {
            feedback.msgError(`请先填写报废仓库`)

        }
    }
    formRef.value?.validate((valid, fields) => {
        if (valid) {
            let arry = tableList.value
            for (var i = arry.length - 1; i >= 0; i--) {
                if (arry[i].title == '') {
                    arry.splice(i, 1)
                }
            }
            for (var i = arry.length - 1; i >= 0; i--) {
                if (arry[i]?.scrap_reason) { } else {
                    arry[i].scrap_reason = ''
                }
            }
            list.items = JSON.stringify(arry)
            const a = JSON.parse(list.items).length
            if (a != 0) {
                mode.value == 'edit' ? onadminEdit() : onadminEdits()
            } else {
                feedback.msgError(`报废物料未添加，请添加报废物料`)
            }

        }
    })

}
const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

const handleClose = () => {
    emit('close')
    userStore.offwarehouse_id()
}
const setFormData = (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}
getOptions()
defineExpose({
    open,
    setFormData
})
</script>
<style scoped lang="scss">
$bor-color: #eeeff0;

::v-deep .el-input.is-disabled .el-input__inner {
    background-color: #fff !important;
    border: 0 !important;
    color: #666666;
    cursor: not-allowed;
}

::v-deep .el-input.is-disabled .el-input__wrapper {
    background-color: #fff !important;
}

::v-deep .el-image__error {
    background-color: #fff !important;
}

::v-deep .el-textarea.is-disabled .el-textarea__inner {
    background-color: #fff !important;
    border-color: #fff !important;
    color: #666666;
    cursor: not-allowed;
}

.fontcolor {
    color: #666666;
}

.el-col {
    border-right: 1px solid $bor-color;
    border-top: 1px solid $bor-color;
    align-items: center;
    padding: 2px;

    &:nth-child(4n) {
        border-right: 0;
    }
}

.el-form-item {
    margin-bottom: 0;
}

::v-deep .el-form-item__label {
    border-left: 0;
    border-top: 0;
    border-bottom: 0;
    margin-right: 10px;
}

.bor {
    border-bottom: 1px solid $bor-color;
    border-left: 1px solid $bor-color;
    border-right: 1px solid $bor-color;

    .bor-title {
        width: 100%;
        height: 40px;
        padding: 10px;
        background-color: #F8F8F8;
    }

    .zhangMain {
        position: absolute;
        right: 30px;
        top: 20px;
        z-index: 0;
        width: 120px;
        height: 120px;
        transform: rotate(20deg);

        .zhang {
            width: 100%;
            height: 100%;
            opacity: 0.6;
        }
    }
}

::v-deep .el-form-item__error {
    z-index: 10;
}

.buts {
    width: 100%;
    height: 50px;
    padding-top: 20px;

    .el-button {
        float: right;
    }
}

.f-left {
    margin-left: 10px;
}

::v-deep .span {
    .el-input__inner {
        width: 133px;
    }

    .el-input__suffix-inner {
        display: none;
    }
}

::v-deep .el-form-item__error {
    top: 80%;
}
</style>